package com.yuyou.fn.platform.service.impl;

import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.JWTToken;
import com.yuyou.fn.platform.service.IAccessTokenService;
import com.yuyou.fn.platform.vo.AccessTokenVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * AccessToken 表数据服务层接口实现类
 */
@Service
public class AccessTokenServiceImpl implements IAccessTokenService {

    private final static Logger log  = LoggerFactory.getLogger(AccessTokenServiceImpl.class);

    private static final long EXPISRATION = 1000 * 60 * 60 * 24 * 1; // 1 days
    private static final String SECRET = "YUYOU@BIG";


    @Override
    public String generateToken(Long userId , String name ,String userType ) {
        Map<String,Object> payload = new HashMap<>();
        payload.put("userId" , String.valueOf(userId));
        payload.put("name" , name );
        payload.put("userType" , userType );
        return JWTToken.generate(name,payload,new Date(System.currentTimeMillis() + EXPISRATION),SECRET );
    }

    public AccessTokenVo validAccessToken( String token) {
        if (StringUtils.isEmpty(token)) {
            throw new BusException("token不能为空");
        }

        try{
            // parse the token.
            Claims claims = JWTToken.parse(token,SECRET);
            if(claims.getSubject() == null){
                return null ;
            }
            String userId = (String)claims.get("userId");
            String name = (String)claims.get("name");

            AccessTokenVo accessTokenVo = new AccessTokenVo();
            accessTokenVo.setToken(token);
            accessTokenVo.setUserId(Long.valueOf(userId));
            accessTokenVo.setName(name);
            return accessTokenVo ;
        }catch (Exception e){
            log.error("parse token fail");
            throw new BusException("accessToken不存在或已过期");
        }


    }


}